CONFIGBOX[CONFIGKEY].version = 50
var $ = Dom7;
var theme = "md";
//是否是本地调试  localhost  192.168.2.36
var isDebug = window.location.host.indexOf("localhost:") > -1 ? true : false;

//切换样式、主题风格
var colorsLa = 'white'; //'white','darkBlueGrey'
//接口上下文路径
var contextPath = CONFIGBOX[CONFIGKEY].proxy || '/';
localStorage.setItem('contextPath', contextPath);
//静态资源上下文路径
var staticPath = common.getRootPath() + (isDebug ? '/' : '/ilink-app-h5-zd/');
var staticPathVue = location.href.indexOf('http://') > -1 ? `${isDebug ? '/' : '/ilink-app-h5-zd/'}ilink-zhxf-h5/` : (staticPath + 'ilink-zhxf-h5/index.html')

//记录用户登录状态，初始化和退出登录的时候改为false：true --> /home/  false --> /login/
var userLoggedIn = false; // 上线的时候改成了false
var userInfor = native.getUserInfor();
//平台Id
let platformCodeId = null;
//存储当前使用的联网单位id
var single_Orgid = "";
var single_OrgName = "";
//维保方卡片用
var single_Orgid_wbdw = "";
var single_OrgName_wbdw = "";
var IfJzwFlag = true
//存储是否在首页切换了单位
var isChangeUnitRole = false;
var isFirstChangeUnit = true;

//获取appkey
var appKeyObj = native.getAppKey();

//获取IOS版本号
var IOSVersion = 0;
//路由集合
var routes = [];
var routes = routes.concat(commomR, messageR, cardsR, applyR, mineR, newCards, newCards2, maintenceKanban);
//巡检code
var PollingCode = '';
//一键报警获取原生定位
var getLoctext = "";
var longitude = "";
var latitude = "";
//点击推送保存的跳转url 分登录和未登录情况
var viewHref = "";
var videoData = [];
var IsNewMsg = false; //是否有新的消息
var loginStatus = native.getDataByKey('loginStatus'); //判断是否自动登录
var startVoice = false;
var photoBrowser = null;
var QrStatus = false;
var changeShiftsType;
var changeShiftForce;
var changeShiftsId;
var shiftStatus;


//用户角色ID集合
let userIdObj = [141, 143, 144, 145, 160, 142, 172, 171, 158, 147, 177, 153, 185, 184, 183];
//九小用户
let nineUserId = [143];
//单单位用户
let singleUserId = [144, 145, 160, 142];
//多单位用户
let moreUserId = [141, 172, 171, 158, 147, 177, 153];
//维保方
let maitenceUserId = [185, 184, 183];
//超级管理员
let adminUserId = [141];

// Init App
var app = new Framework7({
  id: 'ilink',
  version: '',
  root: '#app',
  history: false,
  cache: true, //是否打开 Ajax 缓存。最好启用Ajax缓存，特别是你的页面内容不经常更新的时候。（默认值：true）
  cacheDuration: 1000 * 60 * 10, //Ajax 缓存时间，在缓存有效期内加载页面不会发起新的ajax请求而是直接使用缓存的结果。（默认是 10 分钟）
  cacheIgnore: [], //不希望被缓存的URL，这是一个字符串数组。（默认为空数组）
  cacheIgnoreGetParameters: false, //缓存是否忽略get参数，如果为 "true"，那么像 "about.html?id=2" 和 "about.html?id=3" 将会和 "about.html" 是一样的缓存。（默认值：false）
  theme: theme,
  routes: routes,
  view: { //启用页面缓存机制
    stackPages: true
  },
  touch: {
    tapHold: true, //enable tap hold events
  },
  // navbar: {
  //    scrollTopOnTitleClick: true //  启用后，每次点击导航栏的标题元素都会将相关页面滚动到顶部
  // },
  data: function () { //应用程序根数据,操作 app.data 进行增删改查
    return {
      staticPath: staticPath, //<img src="{{$root.staticPath}}img/beach.jpg">
      areaData: [], //区域数据
      currentActiveTab: "home",
      isFirstLoad: true,
      longitude: 0,
      latitude: 0,
      defaultPlatCode: PLATCOEDEFAULT,
    };
  },
  on: {
    pageAfterIn: function (e) {
      if (changeShiftForce && app.view.current.router.currentPageEl.f7Component && app.view.current.router.currentPageEl.f7Component.pageName == "changeShifts") {
        app.view.current.router.currentPageEl.f7Component.backToRefresh()
      }
      //查找页面是否有input 或者 textarea
      if (jQuery(e.$el).find("input").length > 0) {
        jQuery.each(jQuery(e.$el).find("input"), function (index, val) {
          if (val.placeholder != "搜一搜") {
            jQuery(val).off().on("blur", function () {
              window.scrollTo(0, 0);
            });
          }
        });
      }
      if (jQuery(e.$el).find("textarea.cancle-ios-write").length > 0) {
        jQuery.each(jQuery(e.$el).find("textarea.cancle-ios-write"), function (index, val) {
          jQuery(val).off().on("blur", function () {
            window.scrollTo(0, 0);
          });
        });
      }
      if (app.view.current.history.length == 1) {
        localStorage.setItem("ilink_select_option", '');
      }
    }
  },
  methods: {
    isOfflinWork() { //判断是否在离线维保列表页面
      if (app && app.view && app.view.current.router.currentPageEl.f7Component && app.view.current.router.currentPageEl.f7Component.pageName == "offlineWork") {
        return true
      } else {
        return false
      }
    },
    /**
     * @description 统一返回
     */
    backToTab: function () {
      //特殊页面后期特殊处理
      var hisLength = app.views.current.history.length;
      //判断是从消息页跳转
      if ('/message/' === app.view[app.view.length - 1].history[0] || pushMessageurl === "" || app.view.current.history[hisLength - 1].indexOf(pushMessageurl) > -1) {
        isFromMessage = 0;
        pushMessageurl = "";
      }
      //home
      /* if(hisLength <= 1){
        return;
      } */
      //get preView from history
      app.view.current.router.back(null, {
        animate: false
      });
      // 隐患返回巡检结果页面 刷新巡检
      if ((hisLength, app.view.current.router.history.indexOf("/checkApply/0/0/0/0/") > -1)) {
        // jQuery('#REFRESH_THE_INSPECTION').getRefreshTheInspection();
        // console.log('---------:',app.view.get('#app'))
      }
      if (app.view.current.router.currentPageEl.f7Component && app.view.current.router.currentPageEl.f7Component.backToRefresh) { //普通页面
        app.view.current.router.currentPageEl.f7Component.backToRefresh();
      } else if (!app.view.current.router.currentPageEl.f7Component && app.view.current.router.history.length === 1 &&
        (app.view.current.router.history[0] === '/' || app.view.current.router.history[0].indexOf("/ilink-app-h5-zd") > -1)) { //首页
        var tabArray = ['home', 'monitor', 'apply', 'message', 'mine'];
        var activeTab = app.data.currentActiveTab;
        if (jQuery.inArray(activeTab, tabArray) > -1 && app.view.get('#' + activeTab).router.currentPageEl.f7Component.backToRefresh) {
          app.view.get('#' + activeTab).router.currentPageEl.f7Component.backToRefresh();
        }
      }

      // if (app.views.current.history.length > 2 || formRouter==='/soleKanbanFromUnitSafety/'){
      //   if (formRouter === '/soleKanbanFromUnitSafety/'){
      //     single_Orgid = '';
      //   }

      //   app.router.back(app.views.current.history[hisLength-1]);
      // }else{
      //   var getTabView = app.views.get("#"+app.data.currentActiveTab);
      //   //存在这个view
      //   if(getTabView){
      //     app.view.current.router.back(null,{animate:false});
      //   }
      //   //不存在 creat
      //   else{
      //     app.view.current.router.back(null,{animate:false});
      //     common.loading(1);
      //     app.tab.show("#"+app.data.currentActiveTab);
      //     setTimeout(function(){
      //       if(app.data.currentActiveTab == "home"){
      //         initPage();
      //       }else{
      //         initPage(app.data.currentActiveTab);
      //       }
      //       common.loading(0);
      //     },800);
      //   }
      // }
      // if (formRouter === '/layer3D/' && app.data.currentActiveTab=="home"){
      //     app.view.get("#ninePlace").router.currentPageEl.f7Component.getNineBanner();
      // }

      // //解决我的页面关注刷新问题
      // if(!formRouter && app.data.currentActiveTab=="mine" && app.view.current.history[app.view.current.history.length-1].indexOf("mineFocunsOn")>-1){
      //     app.ptr.refresh();
      // }
    },
    //是否首次进入pageAfterIn
    isFirstPageAfterIn: function (page) {
      return page && page.position === "next";
    },
    refreshMineFocus: function () {
      if (app.view.get("#mine") && app.view.get("#mine").router.currentPageEl.f7Component) {
        app.view.get("#mine").router.currentPageEl.f7Component.refreshCurrent(1, function () { });
      }
    },
    //刷新探测器卡片和列表
    freshEqment: function () {
      //这里的延迟执行解决框架不执行bug
      setTimeout(function () {
        //首页-设备
        if (app.view.get("#focusEquipment") && app.view.get("#focusEquipment").router && app.view.get("#focusEquipment").router.currentPageEl && app.view.get("#focusEquipment").router.currentPageEl.f7Component) {
          app.view.get("#focusEquipment").router.currentPageEl.f7Component.getEquipment();
        }
        //我的关注-设备
        else if ($("#mineFocusOn_tabs_equip").length > 0 && $("#mineFocusOn_tabs_equip").hasClass("tab-link-active")) {
          $("#mineFocusOn_tabs_equip").trigger("click");
        }
      }, 100);

    },
    //刷新视频卡片和列表
    freshVedio: function () {
      //这里的延迟执行解决框架不执行bug
      setTimeout(function () {
        //tab-视频监控
        if (app.view.get("#monitor") && app.view.get("#monitor").router && app.view.get("#monitor").router.currentPageEl && app.view.get("#monitor").router.currentPageEl.f7Component && app.view.get("#monitor").router.currentPageEl.f7Component.focusRefreshView) {
          app.view.get("#monitor").router.currentPageEl.f7Component.focusRefreshView();
        }
        //首页-视频
        if (app.view.get("#focusVedio") && app.view.get("#focusVedio").router && app.view.get("#focusVedio").router.currentPageEl && app.view.get("#focusVedio").router.currentPageEl.f7Component && app.view.get("#focusVedio").router.currentPageEl.getVideoInfo) {
          app.view.get("#focusVedio").router.currentPageEl.f7Component.getVideoInfo();
        }
        //我的关注-视频
        if ($("#mineFocusOn_tabs_vedio").length > 0 && $("#mineFocusOn_tabs_vedio").hasClass("tab-link-active")) {
          $("#mineFocusOn_tabs_vedio").click();
        }
      }, 100);
    },
    //在底部通知。param:｛消息体，多久后消失｝
    showToastBottom: function (msg, time) {
      var self = this;
      // Create toast
      self.toastBottom = app.toast.create({
        text: msg,
        closeTimeout: time == null ? 2000 : time,
      });
      // Open it
      self.toastBottom.open();
    },
    showToastIcon: function (isClose) {
      var self = this;
      // Create toast
      if (!isClose) {
        if (!self.toastIcon) {
          self.toastWithCallback = app.toast.create({
            icon: '<i class="mic-icon"></i>',
            text: '请开始说话',
            position: 'center',
            closeTimeout: 10000,
            // closeButton: true,
            // closeButtonText: 'X',
            // on: {
            //     close: function () {
            //     },
            // }
          });
        }
        self.toastWithCallback.open();
      } else {
        self.toastWithCallback.close();
        self.toastWithCallback = null;
      }
    },
    showToastCenter: function (msg, time) {
      var self = this;
      // Create toast
      self.toastCenter = app.toast.create({
        text: msg,
        position: 'center',
        closeTimeout: time == null ? 2000 : time,
      });
      // Open it
      self.toastCenter.open();
    },
    //系统筛选
    initNewSinglePiker: function (bindDom, callback, valueArr) {
      var self = this;
      var $ = self.$$;
      if (valueArr.length > 0) {
        if (self.pickerSystemToolbar) {
          self.pickerSystemToolbar.destroy();
        }
        self.pickerSystemToolbar = app.picker.create({
          inputEl: '#' + bindDom,
          rotateEffect: true,
          renderToolbar: function () {
            return '<div class="toolbar">' +
              '<div class="toolbar-inner">' +
              '<div class="left">' +
              '<a href="#" class="link sheet-close">取消</a>' +
              '</div>' +
              '<div class="right">' +
              '<a href="#" class="link sheet-close popover-close quit-area">确定</a>' +
              '</div>' +
              '</div>' +
              '</div>';
          },
          cols: [{
            textAlign: 'center',
            values: (function () {
              var map = [];
              for (var property in valueArr) {
                if (valueArr[property]["systemName"] != undefined) {
                  map.push(valueArr[property]["systemName"]);
                }
              }
              return map;
            })(),
          }],
          on: {
            open: function (picker) {
              jQuery(".piker-bg").show();
              picker.$el.find('.quit-area').on('click', function (e, a) {
                var key = [];
                for (var property in valueArr) {
                  key.push(valueArr[property]["systemId"]);
                }
                callback(picker.getValue(), key[picker.cols[0].activeIndex]);
              });
            },
            close: function () {
              jQuery(".piker-bg").hide();
            }
          }
        });
      } else {
        if (self.pickerSystemToolbar) {
          self.pickerSystemToolbar.destroy();
        }
      }
    },
    //保养系统筛选
    BYinitNewSinglePiker: function (bindDom, callback, valueArr) {
      var self = this;
      var $ = self.$$;
      if (valueArr.length > 0) {

        self.pickerSystemToolbar = app.picker.create({
          inputEl: '#' + bindDom,
          rotateEffect: true,
          renderToolbar: function () {
            return '<div class="toolbar">' +
              '<div class="toolbar-inner">' +
              '<div class="left">' +
              '<a href="#" class="link sheet-close">取消</a>' +
              '</div>' +
              '<div class="right">' +
              '<a href="#" class="link sheet-close popover-close quit-area">确定</a>' +
              '</div>' +
              '</div>' +
              '</div>';
          },
          cols: [{
            textAlign: 'center',
            values: (function () {
              var map = [];
              for (var property in valueArr) {
                if (valueArr[property]["systemName"] != undefined) {
                  map.push(valueArr[property]["systemName"]);
                }
              }
              return map;
            })(),
          }],
          on: {
            open: function (picker) {
              jQuery(".piker-bg").show();
              picker.$el.find('.quit-area').on('click', function (e, a) {
                var key = [];
                for (var property in valueArr) {
                  key.push(valueArr[property]["fireSystemId"]);
                }
                callback(picker.getValue(), key[picker.cols[0].activeIndex]);
              });
            },
            close: function () {
              jQuery(".piker-bg").hide();
            }
          }
        });
      } else {
        if (self.pickerSystemToolbar) {
          self.pickerSystemToolbar.destroy();
        }
      }
    },
    //保养 保养人筛选
    BYpreinitNewSinglePiker: function (bindDom, callback, valueArr) {
      var self = this;
      var $ = self.$$;
      if (valueArr.length > 0) {
        self.pickerSystemToolbar = app.picker.create({
          inputEl: '#' + bindDom,
          rotateEffect: true,
          renderToolbar: function () {
            return '<div class="toolbar">' +
              '<div class="toolbar-inner">' +
              '<div class="left">' +
              '<a href="#" class="link sheet-close">取消</a>' +
              '</div>' +
              '<div class="right">' +
              '<a href="#" class="link sheet-close popover-close quit-area">确定</a>' +
              '</div>' +
              '</div>' +
              '</div>';
          },
          cols: [{
            textAlign: 'center',
            values: (function () {
              var map = [];
              for (var property in valueArr) {
                if (valueArr[property]["name"] != undefined) {
                  map.push(valueArr[property]["name"]);
                }
              }
              return map;
            })(),
          }],
          on: {
            open: function (picker) {
              jQuery(".piker-bg").show();
              picker.$el.find('.quit-area').on('click', function (e, a) {
                var key = [];
                for (var property in valueArr) {
                  key.push(valueArr[property]["account"]);
                }
                callback(picker.getValue(), key[picker.cols[0].activeIndex]);
              });
            },
            close: function () {
              jQuery(".piker-bg").hide();
            }
          }
        });
      } else {
        if (self.pickerSystemToolbar) {
          self.pickerSystemToolbar.destroy();
        }
      }
    },
  }
});

//color Theme
//dark  light
var bgtheme = "light";
var colors = ['red', 'green', 'blue', 'pink', 'yellow', 'orange', 'gray', 'black'];
app.root.removeClass('theme-dark theme-light').addClass('theme-' + bgtheme);
var nowtheme = 'la-themes-' + colorsLa;
app.root.addClass(nowtheme);

var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'css/themes/' + colorsLa + '/color.css';
document.getElementsByTagName('head')[0].appendChild(link);


//图表换肤
var chatFontColor = "";
if (colorsLa == 'darkBlueGrey') { //黑色
  chatFontColor = '#fff';
  chatLineColor = 'rgba(255, 255, 255, 0.3)';
} else if (colorsLa == 'white') { //白色
  chatFontColor = "#666";
  chatLineColor = '#666';
};